﻿using DotNetty.Codecs.Http.WebSockets;
using DotNetty.Transport.Channels;
using System;
using System.Text;

namespace DotNetty.Framework
{
    /// <summary>
    /// 文本处理类
    /// </summary>
    public class TextWebSocketHandler<TMessage> : SimpleChannelInboundHandler<TextWebSocketFrame>
        where TMessage : AbstractMessage
    {

        IWebSocketEventTriggered<TMessage> eventTriggered;

        public TextWebSocketHandler(IWebSocketEventTriggered<TMessage> eventTriggered)
        {
            this.eventTriggered = eventTriggered;
        }

        protected async override void ChannelRead0(IChannelHandlerContext ctx, TextWebSocketFrame msg)
        {
            try
            {
                if (Common.IsShutdowned)
                {
                    return;
                }

                // 消息内容
                var messageOfString = msg.Content.ToString(Encoding.UTF8);

                if (messageOfString != "h")
                {
                    // 是否是心跳
                    if (!string.IsNullOrWhiteSpace(messageOfString) & messageOfString?.Length > 1)
                    {
                        // 消息实体
                        var message = Newtonsoft.Json.JsonConvert.DeserializeObject<TMessage>(messageOfString);
                        await this.eventTriggered.OnMessage(ctx, message);
                    }
                }

            }
            catch (Exception ex)
            {
                await this.eventTriggered.OnError(ctx, new OnExceptionContext
                {
                    Action = "TextWebSocketHandler.ChannelRead0",
                    Exception = ex,
                    Message = msg
                });
            }
            finally
            {
                //if (msg.ReferenceCount > 0)
                //{
                //    msg.Release();
                //}
            }
        }
    }
}
